﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxChatWebApp.DTO;

namespace AjaxChatWebApp
{
    public partial class YahooNewsPage : System.Web.UI.Page
    {
        HttpClient httpClient = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {           
            httpClient.BaseAddress = new Uri("http://localhost:62865");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            if(!IsPostBack)
            {
                rbCategory_CheckedChanged(rbEntertainment, e);
            }
        }

        protected void rbCategory_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton) sender;
            if(rb.Checked)
            {
                string category = rb.Text.ToLower();
                List<RssItem> feeds = GetFeeds(category);
                dlFeeds.DataSource = feeds;
                dlFeeds.DataBind();
            }
        }

        private List<RssItem> GetFeeds(string category)
        {
            List<RssItem> feeds = new List<RssItem>();

            HttpResponseMessage response = httpClient.GetAsync("api/rssyahoo?category=" + category).Result;
            if(response.IsSuccessStatusCode)
            {
                feeds = response.Content.ReadAsAsync<IEnumerable<RssItem>>().Result.ToList();
            }

            return feeds;
        }
    }
}